package App.Utility;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

public class RSADecrypt {

    public static void main(String[] args) throws Exception {
        String encrypted = "AKWVa/R64vP3DsRD2zLvnoshTGTeiYT5P7nd9rMuH4ORWZGsThoHmdHyrpRRyFrNenaMHTfO5CHpdk61Rk9pvrJFotmZHtGRh96pbUNFjwucQ8BYTOiKzgB0Ae/9SGT4MXaDYrDvxYBgtST4HuEUkzk+IYw3vKh+Nq4x+srjbrA=";
        String prikey = "\n" +
                "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALqiTpPKUOkbv7HC\n" +
                "+jgITKBmpBK1YcQZpyCXvHf2Oz5Lki+s77qnIKBzK6Xl71ZaWbSz7Rvaagv9V2U5\n" +
                "bjhIX6n2odfc5+ArMoVxWn9ePPiPX0GtTCFznPmOZhrOlELmYdVTSfLRbsAvHild\n" +
                "nETupA5qj+hmp9iTmQGQ51Zc+I3JAgMBAAECgYAD5goQKkTAadT6SKFjdEDthNde\n" +
                "kK1nJEYKd0D3nIwmQ/vcxRcI5h7XWzCJOaFjQ2XmUW/dihV3BKbDtYxo3pIo+I2S\n" +
                "r30Py8NiRqHjU8szniYRFBr/n6gEu3oGxmiNlUPpfXP2KaG/1yvje0IRjyisBC9Q\n" +
                "OqD75P/xx5DGx8WOkQJBAPVKmEqcb9coD2cKSfsyPXeLKVMgb931a8UUpqx2Hw+R\n" +
                "+vYi9+t7HdrFlxDqk+dtnAKJlmCidJaJb3cq7U0byh0CQQDCyCaAk8D1AykuX4zG\n" +
                "PSSua7U2ENEQlDhsPQYY5Lu3HeB3bzus7w7NkjtRdAQzHStfvDEfabXlh3pBpkes\n" +
                "gOKdAkBdSvfNON6YuJXTHOiyb5NNSlJ3WVjy1IsetBIIegyqQV1wDDC7EWJzeL9S\n" +
                "IcYLOXcix+2351Hsh20rp9oFf9JJAkBVk0vfJ4sZ2haoqhAWNFy+SNHnfAHuD8Cu\n" +
                "RS09mJikPfsVXghQ1QKi7IElKxyBPGqG+A5455+jxR7AYwaQUlu9AkAZltgBdPEZ\n" +
                "6kh314JnXDnxy8K7LPeO/HGh9lUD+0Pc89gJWqJubULKZjJcLZOwLL+vbnGyiyYw\n" +
                "Ujs36CFvXCo9\n" +
                "\n";

        String result = decrypt(encrypted, prikey);
        System.out.println(result);
    }

    public static String decrypt(String cryptograph, String prikey) throws Exception {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodeStr(prikey));
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec);

        Cipher cipher=Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        byte [] b = decodeStr(cryptograph);
        return new String(cipher.doFinal(b));
    }

    /**
     * 解密
     *
     * @param pwd
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static byte[] decodeStr(String pwd)
    {
        Base64 base64 = new Base64();
        byte[] debytes = base64.decodeBase64(new String(pwd).getBytes());
        return debytes;
    }

    /**
     * 加密
     *
     * @param pwd
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String encodeStr(String pwd)
    {
        Base64 base64 = new Base64();
        byte[] enbytes = base64.encodeBase64Chunked(pwd.getBytes());
        return new String(enbytes);
    }

}
